package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.model.User;
import com.example.forum.service.impl.UserServiceImpl;
import com.example.forum.utils.JWTUtils;
import com.example.forum.utils.Md5Utils;
import com.example.forum.utils.UUIDUtils;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api("用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserServiceImpl userService;

    /**
     * 注册用户
     * @param username 用户名称
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名称") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验数据是否传递正确
//        if(StringUtils.hasLength(user.getUser_name()) ||
//            StringUtils.hasLength(user.getNickname()) ||
//            StringUtils.hasLength(user.getPassword()) ||
//            passwordRepeat.length() < 0) {
//            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //校验密码与重复密码是否相同
        if(!password.equals(passwordRepeat)) {
            log.error(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUser_name(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtils.UUID_32();
        //最终password与salt生成的密文
        String finalPassword = Md5Utils.md5Salt(password,salt);
        user.setPassword(finalPassword);
        user.setSalt(salt);
        userService.createNormalUser(user);
        log.info("注册成功");
        return AppResult.success("注册成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("用户密码") @RequestParam("password") @NonNull String password) {
//        if(!StringUtils.hasLength(username)
//                || !StringUtils.hasLength(password)) {
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage() + ",username = " + username);
//            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        User user = userService.login(username,password);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_EXISTS.getMessage() + ",username = " + username);
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        /*生成令牌*/
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",username);
        claims.put("id", String.valueOf(user.getId()));
//        claims.put("id",user.getId());
        String jwt = JWTUtils.genJwt(claims);
        System.out.println("jwt: " + jwt);
        return  AppResult.success("success",jwt);
    }

    @ApiOperation("获取用户信息")
    @RequestMapping("/info")
    public AppResult info(@ApiParam("用户id") @RequestParam(value = "id",required = false)Long id,
                          HttpServletRequest request) {
        Long userId = null;
        if(id == null) {
            String jwt = request.getHeader("user_token");
            String stringId = JWTUtils.getUserId(jwt);
            userId = Long.parseLong(stringId);
            if (userId == null || userId < 0) {
                log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage() + "userId = " + userId);
                return AppResult.fail(ResultCode.FAILED_NOT_EXISTS);
            }
        }else {
            userId = id;
        }
        User user = userService.getUserInfo(userId);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("用户退出")
    @RequestMapping("/logout")
    public AppResult logout() {
        return AppResult.success("退出成功");
    }


    @ApiOperation("修改用户信息")
    @RequestMapping("/modifyInfo")
    public AppResult modifyInfo(@ApiParam("用户信息") @NonNull User user,HttpServletRequest request) {
        String stringId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringId);
        user.setId(userId);
        Integer ret = userService.updateUser(user);
        if(ret == null) {
            return AppResult.fail("更新失败");
        }
        return AppResult.success("更新成功");

    }


    @ApiOperation("更改密码")
    @RequestMapping("/modifyPwd")
    public AppResult modifyPwd(@RequestParam("oldPassword") @ApiParam("旧密码") @NonNull String oldPassword,
                               @RequestParam("newPassword") @ApiParam("新密码") @NonNull String newPassword,
                               @RequestParam("passwordRepeat") @ApiParam("确认密码") @NonNull String passwordRepeat,
                               HttpServletRequest request) {
        if(oldPassword.equals(newPassword) || !newPassword.equals(passwordRepeat)) {
            return AppResult.fail("更新密码失败");
        }
        String stringId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringId);
        Integer ret = userService.updateUserPassword(userId,passwordRepeat);
        if(ret == null || ret <= 0) {
            return AppResult.fail("更改密码失败");
        }

        return AppResult.success("更改密码成功");
    }

    @ApiOperation("上传图片")
    @RequestMapping("/load")
    public AppResult load(@RequestPart @NonNull MultipartFile file,HttpServletRequest request) {
        String stringId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringId);
        String filename = file.getOriginalFilename();
        String ret = userService.loadUserPhoto(filename,file,userId);
        if(ret == null) {
            return AppResult.fail("上传图片失败");
        }
        return AppResult.success("上传成功",ret);
    }
}
